from sqlalchemy import Column, DateTime, func, TIMESTAMP
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import declarative_mixin


class TimestampMixin:
    @declared_attr
    def ctime(cls):
        '''
        创建时间
        :return:
        '''
        return Column(DateTime, default=func.now(), nullable=False)

    @declared_attr
    def utime(cls):
        '''
        更新时间
        :return:
        '''
        return Column(
            DateTime,
            default=func.now(),
            onupdate=func.now(),
            nullable=False,
        )


@declarative_mixin
class CTimeMixin:
    """Mixin for add created_at field."""

    ctime = Column(
        TIMESTAMP(timezone=True),
        server_default=func.current_timestamp(),
        nullable=False,
    )


@declarative_mixin
class UTimeMixin:
    """Mixin for add updated_at field."""

    utime = Column(
        TIMESTAMP(timezone=True),
        server_default=func.current_timestamp(),
        server_onupdate=func.current_timestamp(),
        nullable=False,
    )


@declarative_mixin
class CreatedUpdatedMixin(CTimeMixin, UTimeMixin):
    """Mixin for add updated_at and created_at fields."""
    pass
